package com.viu.technology.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import sun.net.util.IPAddressUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;

/**
 * 日志拦截器，用于记录请求的时长、IP、参数等
 */
public class LogHandlerInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(LogHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //由于使用的是jwt认证方式，所以不保存请求机器的session
        //String sessionId = request.getRequestedSessionId();
        String uri = request.getRequestURI();
        String param = JSONObject.toJSON(request.getParameterMap()).toString();
        String ip = getIpAddr(request);
        String method = request.getMethod();
        long startTime = System.currentTimeMillis();

        JSONObject object = new JSONObject();
        //object.put("sessionId", sessionId);
        object.put("uri", uri);
        object.put("param", param);
        object.put("ip", ip);
        object.put("method", method);
        object.put("startTime", startTime);
        request.setAttribute("LOGGER", object);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求结束后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        JSONObject object = (JSONObject) request.getAttribute("LOGGER");
/*        log.info("ip:"+object.get("ip")+"\n" +
                "time:"+(System.currentTimeMillis()-(long)object.get("startTime")));*/

        log.info("time:"+(System.currentTimeMillis()-(long)object.get("startTime")));

    }

    /**
     * 获取请求地址IP
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if(ip.equals("127.0.0.1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
            }
        }
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ip != null && ip.length() > 15){
            if(ip.indexOf(",")>0){
                ip = ip.substring(0,ip.indexOf(","));
            }
        }
        return ip;
    }
}
